package com.yaodian100.ec.shelf.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.ObjectDao;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.ProductTuangouOP;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.shelf.entity.ShelfTuangou;
import com.yaodian100.ec.shelf.service.ShelfTuangouService;

public class ShelfTuangouServiceImpl extends DomainServiceImpl<ShelfTuangou> implements ShelfTuangouService {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private BaseManager baseManager;
	@Resource
	private LogService logService;

	private final static String[] SORT_BY = new String[] { "startDate desc", "modifyDate desc" };

	private final String finalStatus = "SHF500";
	private ObjectDao<ProductTuangouOP> opDao;
	@Autowired
	private Product2Service productService;

	@Autowired
	private TemplateService templateService;

	@Override
	public ShelfTuangou getShelfTuangouByProductId(String productId, Date startDate, Date endDate) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("productId", productId);
		crit.addLe("startDate", startDate);
		crit.addGe("endDate", endDate);
		crit.addEq("status", finalStatus);

		List<ShelfTuangou> shelfTuangouList = this.getDao().getList(crit, SORT_BY);
		if (null != shelfTuangouList && !shelfTuangouList.isEmpty() && shelfTuangouList.size() > 0) {
			return shelfTuangouList.get(0);
		} else {
			return null;
		}
	}

	@Override
	public ShelfTuangou getActiveShelfTuangouByProductId(String productId) {
		Date now = DateUtil.getCurrentTime();
		ShelfTuangou shelfTuangou = this.getShelfTuangouByProductId(productId, now, now);

		return shelfTuangou;
	}

	@Override
	public List<Map<String, Object>> getShelfTuangouHistory(String productId) {
		String sql = "SELECT * FROM EC_SHELF_TUANGOU_HISTORY WHERE PRODUCT_ID=? AND STATUS IN ('SHF000','SHF500') "
				+ "AND (SYSDATE BETWEEN START_DATE AND END_DATE OR START_DATE >= SYSDATE OR END_DATE >= SYSDATE)";
		List<Map<String, Object>> shelfTuangouHistoryList = jdbcTemplate.queryForList(sql, new Object[] { productId });

		return shelfTuangouHistoryList;
	}

	@Override
	public boolean checkShelfTuangouDate(String productId, String sDate, String sTime, String eDate, String eTime) {
		String sql = "SELECT COUNT(*) FROM EC_SHELF_TUANGOU WHERE PRODUCT_ID=? AND STATUS IN ('SHF000','SHF500') "
				+ "AND ((TO_CHAR(START_DATE,'YYYY-MM-DD HH24:MI:SS')<=? AND TO_CHAR(END_DATE,'YYYY-MM-DD HH24:MI:SS')>=?) "
				+ "OR (TO_CHAR(START_DATE,'YYYY-MM-DD HH24:MI:SS')<=? AND TO_CHAR(END_DATE,'YYYY-MM-DD HH24:MI:SS')>=?))";

		String startDate = sDate + " " + sTime + ":00";
		String endDate = eDate + " " + eTime + ":59";
		int count = jdbcTemplate.queryForInt(sql, productId, startDate, startDate, endDate, endDate);
		if (count > 0)
			return false;

		return true;
	}

	@Override
	@Transactional(readOnly = false)
	public ShelfTuangou saveOrUpdateShelfTuangou(ShelfTuangou shelfTuangou) throws CoreException {
		try {
			this.getDao().saveOrUpdate(shelfTuangou);
			logService.save(getClass().getSimpleName(), "saveOrUpdateShelfTuangou", shelfTuangou);
		} catch (CoreException e) {
			throw new CoreException("新增/修改团购活动上架檔失败");
		}

		return shelfTuangou;
	}

	@Override
	@Transactional(readOnly = false)
	public ProductTuangouOP saveTuangouOPLog(ProductTuangouOP op) throws CoreException {
		return getOpDao().save(op);
	}

	@Override
	public Number getShelfTuangouApproveListSize(Map<String, Object> attrs) {
		StringBuilder sb = new StringBuilder();
		sb.append("select count(st) from ShelfTuangou st , Product p where st.productId = p.productId ");
		sb.append("and p.productType != '6' ");
		if (attrs.size() > 0) {
			if (null != attrs.get("createDate")) {
				sb.append("and st.createDate >= :createDate ");
			}
			if (null != attrs.get("createUser")) {
				sb.append("and st.createUser = :createUser ");
			}
			if (null != attrs.get("status")) {
				sb.append("and st.status = :status ");
			}
			if (null != attrs.get("productId")) {
				sb.append("and st.productId = :productId ");
			}
			if (null != attrs.get("productName")) {
				sb.append("and p.productName like :productName ");
			}
		}
		List<Object> objs = getDao().getQueryByMap(sb.toString(), attrs, 0, -1);
		sb.setLength(0);
		if (objs.size() > 0) {
			return NumberUtils.createNumber(objs.get(0).toString());
		} else {
			return 0;
		}
	}

	@Override
	public List<ShelfTuangou> getShelfTuangouApproveList(Map<String, Object> attrs, String[] sortBy, int startNode,
			int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append("select st from ShelfTuangou st , Product p where st.productId = p.productId ");
		sb.append("and p.productType != '6' ");
		if (attrs.size() > 0) {
			if (null != attrs.get("createDate")) {
				sb.append("and st.createDate >= :createDate ");
			}
			if (null != attrs.get("createUser")) {
				sb.append("and st.createUser = :createUser ");
			}
			if (null != attrs.get("status")) {
				sb.append("and st.status = :status ");
			}
			if (null != attrs.get("productId")) {
				sb.append("and st.productId = :productId ");
			}
			if (null != attrs.get("productName")) {
				sb.append("and p.productName like :productName ");
			}
		}
		List<ShelfTuangou> shelfTuangous = getDao().getQueryByMap(sb.toString(), attrs, startNode, pageSize);
		sb.setLength(0);
		return shelfTuangous;
	}

	@Override
	public ProductTuangouOP queryOrderOperator(String tuangouId) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("tuangouId", tuangouId);
		List<ProductTuangouOP> list = this.getOpDao().getList(crit, null);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}

		return null;
	}

	@Override
	public ShelfTuangou getShelfTuangouByTuangouId(Long tuangouId, Date startDate, Date endDate) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("tuangouId", tuangouId);
		if (startDate != null)
			crit.addLe("startDate", startDate);
		if (endDate != null)
			crit.addGe("endDate", endDate);
		crit.addEq("status", finalStatus);

		List<ShelfTuangou> shelfTuangouList = this.getDao().getList(crit, null);
		if (null != shelfTuangouList && !shelfTuangouList.isEmpty() && shelfTuangouList.size() > 0) {
			return shelfTuangouList.get(0);
		} else {
			return null;
		}
	}

	@Override
	public ShelfTuangou getActiveShelfTuangouByTuangouId(Long tuangouId) {
		Date now = DateUtil.getCurrentTime();
		ShelfTuangou shelfTuangou = this.getShelfTuangouByTuangouId(tuangouId, now, now);

		return shelfTuangou;
	}

	@Override
	public List<ShelfTuangou> getTodayTuangouList(Long nowTuangouId) throws ParseException {
		CommonCriteria crit = new CommonCriteria();
		crit.addNe("tuangouId", nowTuangouId);

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String todayStr = df.format(new Date());
		String todayStart = todayStr + " 00:00:00";
		String todayEnd = todayStr + " 23:59:59";
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		crit.addLe("startDate", df.parse(todayStart));
		crit.addGe("endDate", df.parse(todayEnd));
		crit.addEq("status", finalStatus);

		String[] sortArray = new String[] { "sortSeq asc", "modifyDate desc", "price asc" };
		List<ShelfTuangou> todayTuangouList = this.getDao().getListPageable(crit, sortArray, 0, 5);

		return todayTuangouList;
	}

	@Override
	public Map<String, String> getTodayPrdNameMap(List<ShelfTuangou> todayTuangouList) {
		if (todayTuangouList == null)
			return null;

		Map<String, String> prdNameMap = new TreeMap<String, String>();
		String sql = "SELECT PRODUCT_NAME FROM EC_PRODUCT_MAIN WHERE PRODUCT_ID = ?";
		for (int i = 0; i < todayTuangouList.size(); i++) {
			ShelfTuangou todayTuangou = todayTuangouList.get(i);
			Map<String, Object> tempMap = jdbcTemplate.queryForMap(sql, new Object[] { todayTuangou.getProductId() });
			prdNameMap.put(todayTuangou.getTuangouId() + "", tempMap.get("PRODUCT_NAME") + "");
		}

		return prdNameMap;
	}

	@Override
	public List<ShelfTuangou> getHistoryTuangouList(int startNode, int returnSize) throws ParseException {
		CommonCriteria crit = new CommonCriteria();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// crit.addLe("startDate", DateUtil.getTodayAddDays(-1).getTime());
		crit.addGe("endDate", DateUtil.getTodayAddDays(-91).getTime());
		crit.addLe("endDate", DateUtil.getToday().getTime());
		crit.addEq("status", finalStatus);
		String[] sortArray = new String[] { "salesType desc", "sortSeq asc", "modifyDate desc", "price asc" };
		List<ShelfTuangou> historyTuangouList = this.getDao().getListPageable(crit, sortArray, startNode, returnSize);
		return historyTuangouList;
	}

	@Override
	public Map<String, Product> getPrdMap(List<ShelfTuangou> tuangouList) {
		Map<String, Product> prdMap = new TreeMap<String, Product>();
		if (tuangouList.size() > 0) {
			List<String> prodIdlist = new ArrayList<String>();
			for (int i = 0; i < tuangouList.size(); i++) {
				prodIdlist.add(tuangouList.get(i).getProductId());
			}
			CommonCriteria crit = new CommonCriteria();
			crit.addIn("productId", prodIdlist);
			List<Product> pdList = productService.getList(0, -1, crit, null);
			for (int i = 0; i < pdList.size(); i++) {
				prdMap.put(pdList.get(i).getProductId(), pdList.get(i));
			}
		}
		return prdMap;

	}

	@Override
	public Map<String, Integer> getInvetoryMap(Map<String, Product> prdMap) {
		if (prdMap == null)
			return null;
		Map<String, Integer> invMap = new TreeMap<String, Integer>();
		invMap = productService.getSpecInventorySum(prdMap);
		return invMap;
	}

	@Override
	public boolean generateActivityList() throws ParseException, CoreException, IOException {
		CommonCriteria crit = new CommonCriteria();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String todayStr = df.format(new Date());
		String todayStart = todayStr + " 00:00:00";
		String todayEnd = todayStr + " 23:59:59";
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		crit.addLe("startDate", new Date());
		crit.addGe("endDate", new Date());
		crit.addEq("status", finalStatus);
		String[] sortArray = new String[] { "sortSeq asc", "modifyDate desc", "price asc" };
		List<ShelfTuangou> todayTuangouList = this.getDao().getListPageable(crit, sortArray, 0, -1);
		Map<String, Product> prdMap = getPrdMap(todayTuangouList);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("onlineList", todayTuangouList);
		m.put("getPrdMap", prdMap);
		m.put("imgDomain", ServerValue.getImgDomain());
		m.put("frontendContextPath", ServerValue.getFrontContextPath());
		logger.error("todayTuangouList.size():{}", todayTuangouList.size());
		if (todayTuangouList.size() > 0) {
			// 折扣
			Map<String, BigDecimal> discountMap = new TreeMap<String, BigDecimal>();
			BigDecimal discount = new BigDecimal("0");
			for (int i = 0; i < todayTuangouList.size(); i++) {
				ShelfTuangou todayTuangou = todayTuangouList.get(i);
				discount = todayTuangou.getPrice()
						.divide(prdMap.get(todayTuangou.getProductId()).getListPrice(), 2, BigDecimal.ROUND_HALF_UP)
						.multiply(new BigDecimal(10));
				discountMap.put(todayTuangou.getProductId(), discount);
			}
			m.put("discountMap", discountMap);
			// 檢查庫存
			Map<String, Integer> invMap = getInvetoryMap(prdMap);
			m.put("invMap", invMap);
		}
		StringBuilder htmlFilePath = new StringBuilder();
		htmlFilePath.append(ServerValue.getFrontApachePath()).append("tuangou").append(File.separator).append("com")
				.append(File.separator).append("tuangouActivity.html");
		FileUtils.writeStringToFile(new File(htmlFilePath.toString()), templateService.format("static_TuangouActivity", m));

		return true;
	}

	// getter & setter
	/**
	 * @return the opDao
	 */
	public ObjectDao<ProductTuangouOP> getOpDao() {
		return opDao;
	}

	/**
	 * @param opDao the opDao to set
	 */
	public void setOpDao(ObjectDao<ProductTuangouOP> opDao) {
		this.opDao = opDao;
	}
}